package com.abu.message.listener;


import cn.hutool.core.util.StrUtil;
import com.abu.common.exception.CRException;
import com.abu.message.utils.CodeUtil;
import com.abu.message.utils.QQMailTemplate;
import com.abu.message.utils.SmsTemplate;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class EmailMessageRabbitmqListener {

    //    邮箱
    private static final String CODE_EXCHANGE = "REGISTER_CODE_EXCHANGE";
    private static final String CODE_ROUTING = "CODE_EMAIL";
    private static final String CODE_QUEUE = "REGISTER_CODE_ROUTING";

    @Autowired
    private QQMailTemplate mailTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String REGISTER = "REGISTER.CODE.";



    /**
     * 普通用户注册验证码
     *
     * @param email
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = CODE_QUEUE, ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(name = CODE_EXCHANGE, ignoreDeclarationExceptions = "true", type = "direct"),
            key = {CODE_ROUTING}
    ))
    public void sendMsg(String email) {
//        生成验证码
        String code = CodeUtil.generator(4);
//        发送验证码到邮箱
        String text = StrUtil.format("  <div>\n" +
                "    您的注册验证码为\n" +
                "    <span style=\"color:blue\">{}</span>，有效期为5分钟，请及时填写\n" +
                "  </div>", code);
        String subject = "<<阿布校理>>";
        try {
            this.mailTemplate.sendHtml(email, subject, text);
        } catch (MessagingException e) {
            log.error("发送邮件失败");
        }
//        缓存中保存一份验证码
        this.stringRedisTemplate.opsForValue().set(REGISTER + email, code, 5, TimeUnit.MINUTES);
    }

}
